package com.lexue.articlesync.adapter;

import com.lexue.articlesync.entity.PlatformAuth;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * 抽象平台适配器基类
 */
@Slf4j
public abstract class AbstractPlatformAdapter implements PlatformAdapter {
    
    @Value("${app.platform.timeout:30000}")
    protected int timeoutMs;
    
    protected OkHttpClient httpClient;
    
    public AbstractPlatformAdapter() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
    }
    
    /**
     * 创建HTTP请求构建器
     */
    protected Request.Builder createRequestBuilder() {
        return new Request.Builder()
                .addHeader("User-Agent", "ArticleSync/1.0")
                .addHeader("Accept", "application/json")
                .addHeader("Content-Type", "application/json; charset=utf-8");
    }
    
    /**
     * 添加认证头
     */
    protected Request.Builder addAuthHeaders(Request.Builder builder, PlatformAuth auth) {
        // 优先使用cookies，如果存在的话
        if (auth.getCookies() != null && !auth.getCookies().trim().isEmpty()) {
            builder.addHeader("Cookie", auth.getCookies());
        }
        
        // 再添加传统的Authorization头
        if (auth.getAccessToken() != null && !auth.getAccessToken().trim().isEmpty()) {
            builder.addHeader("Authorization", "Bearer " + auth.getAccessToken());
        }
        
        return builder;
    }
    
    /**
     * 执行HTTP请求
     */
    protected Response executeRequest(Request request) throws IOException {
        try {
            Response response = httpClient.newCall(request).execute();
            log.debug("HTTP请求: {} {}, 响应状态: {}", 
                    request.method(), request.url(), response.code());
            return response;
        } catch (IOException e) {
            log.error("HTTP请求失败: {} {}", request.method(), request.url(), e);
            throw e;
        }
    }
    
    /**
     * 检查认证是否过期
     */
    protected boolean isAuthExpired(PlatformAuth auth) {
        if (auth.getTokenExpiresAt() == null) {
            return false;
        }
        return LocalDateTime.now().isAfter(auth.getTokenExpiresAt());
    }
    
    /**
     * 处理API错误响应
     */
    protected String handleErrorResponse(Response response) throws IOException {
        String errorBody = response.body() != null ? response.body().string() : "未知错误";
        String errorMessage = String.format("API请求失败: %d %s - %s", 
                response.code(), response.message(), errorBody);
        log.error(errorMessage);
        return errorMessage;
    }
    
    /**
     * 构建发布失败结果
     */
    protected PublishResult buildFailureResult(String errorMessage) {
        return new PublishResult(false, errorMessage);
    }
    
    /**
     * 构建发布成功结果
     */
    protected PublishResult buildSuccessResult(String contentId, String contentUrl) {
        return new PublishResult(true, contentId, contentUrl);
    }
    
    /**
     * 验证必要参数
     */
    protected void validateRequired(Object value, String paramName) {
        if (value == null || (value instanceof String && ((String) value).trim().isEmpty())) {
            throw new IllegalArgumentException(paramName + " 不能为空");
        }
    }
    
    /**
     * 清理和格式化标签
     */
    protected String formatTags(String tags) {
        if (tags == null || tags.trim().isEmpty()) {
            return "";
        }
        
        // 清理标签：移除特殊字符，用逗号分隔
        return tags.replaceAll("[^\\u4e00-\\u9fa5a-zA-Z0-9\\s,，]", "")
                .replaceAll("[，]", ",")
                .replaceAll("\\s+", "")
                .replaceAll(",+", ",")
                .replaceAll("^,|,$", "");
    }
    
    /**
     * 限制文本长度
     */
    protected String limitLength(String text, int maxLength) {
        if (text == null) {
            return "";
        }
        if (text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength - 3) + "...";
    }
    
    /**
     * 默认的认证验证实现
     */
    @Override
    public boolean validateAuth(PlatformAuth auth) {
        if (auth == null || !auth.isValid()) {
            return false;
        }
        
        if (isAuthExpired(auth)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 默认的认证刷新实现（子类可以重写）
     */
    @Override
    public PlatformAuth refreshAuth(PlatformAuth auth) {
        log.warn("平台 {} 未实现认证刷新功能", getPlatformCode());
        return auth;
    }
    
    /**
     * 默认的状态检查实现（子类可以重写）
     */
    @Override
    public PublishStatus checkPublishStatus(String platformContentId, PlatformAuth auth) {
        log.warn("平台 {} 未实现状态检查功能", getPlatformCode());
        return PublishStatus.SUCCESS;
    }
    
    /**
     * 默认的内容删除实现（子类可以重写）
     */
    @Override
    public boolean deleteContent(String platformContentId, PlatformAuth auth) {
        log.warn("平台 {} 未实现内容删除功能", getPlatformCode());
        return false;
    }
}